﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Gif.Components;
using MKAdmin.ToolKit.FileKit;

namespace MKAdmin.ToolKit
{
    public class FileHelper
    {
        /// <summary>
        /// 非群管理图片文件
        /// </summary>
        /// <param name="mFile"></param>
        /// <returns></returns>
        public static string GetMFileUrl(string mFile)
        {
            if (!string.IsNullOrEmpty(mFile) && mFile.IndexOf("http") != 0)
            {
                string serversDomain = AppSettingsKit.GetValue("ServersDomain");
                string fileName = string.IsNullOrEmpty(mFile) ? "" : mFile.Replace("\\", "/");
                return string.Format("{0}/{1}/{2}", serversDomain, "_uploadfile", fileName);
            }
            return mFile;
        }

        /// 群管理图片文件
        /// </summary>
        /// <param name="mFile"></param>
        /// <returns></returns>
        public static string GetGroupFileUrl(string mFile, string key)
        {
            if (string.IsNullOrEmpty(mFile))
            {
                return "";
            }
            if (mFile.IndexOf("http") == 0)
            {
                return mFile;
            }
            var catalogElement = FileCatalogHelper.Catalog[key];
            mFile = string.IsNullOrEmpty(mFile) ? "" : mFile.Replace("\\", "/");

            return string.Format("{0}/{1}", catalogElement.DestFile.RelativePath, mFile);
        }

        #region Copy图片到所选配置目录下并返回图片可访问的相对位置
        /// <summary>
        /// Copy图片到所选配置目录下并返回图片可访问的相对位置
        /// </summary>
        /// <param name="key">配置文件KEY</param>
        /// <param name="catalog">图片目录</param>
        /// <param name="filename">图片文件名</param>
        /// <returns>可访问的相对位置</returns>
        public static string CopyFile(string key, string catalog, string filename)
        {
            if (string.IsNullOrEmpty(catalog))
            {
                return "";
            }
            CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];

            //Copy图片到目标目录下
            //获取临时目录
            string tempFilePath = $@"{catalogConfig.TempFile.AbsolutePath}{catalog.Replace("/", "\\")}";
            tempFilePath = Path.Combine(tempFilePath, filename);

            //获取目标目录
            string targetFilePath = $@"{catalogConfig.DestFile.AbsolutePath}{catalog.Replace("/", "\\")}";

            if (!Directory.Exists(targetFilePath))
            {
                Directory.CreateDirectory(targetFilePath);
            }

            targetFilePath = Path.Combine(targetFilePath, filename);
            //正式目录中不存在且临时目录存在,则执行复制操作
            if (!File.Exists(targetFilePath) && File.Exists(tempFilePath))
            {
                File.Copy(tempFilePath, targetFilePath, true);
            }

            //获取正式文件相对路径
            string urlFilePath = $@"{catalogConfig.DestFile.RelativePath}{catalog}";
            urlFilePath = $@"{urlFilePath}{filename.Replace("\\", "/")}";

            return urlFilePath;
        }
        #endregion

        #region Copy图片到所选配置目录下并返回图片可访问的相对位置
        /// <summary>
        /// Copy图片到所选配置目录下并返回图片可访问的相对位置
        /// </summary>
        /// <param name="originalKey"></param>
        /// <param name="originalVisitCatalog"></param>
        /// <param name="newKey"></param>
        /// <param name="newVisitCatalog"></param>
        /// <param name="catalog">文件目录</param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string CopyFile(string originalKey, VisitCatalog originalVisitCatalog,
        string newKey, VisitCatalog newVisitCatalog, string catalog, string filename)
        {
            if (string.IsNullOrEmpty(originalKey) || string.IsNullOrEmpty(newKey))
            {
                return "";
            }
            CatalogElement originalCatalogConfig = FileCatalogHelper.Catalog[originalKey];
            CatalogElement newCatalogConfig = FileCatalogHelper.Catalog[newKey];

            //获取需要复制的图片目录
            string originalFilePath = "";
            if (originalVisitCatalog == VisitCatalog.TempCatalog)
            {
                originalFilePath = Path.Combine(originalCatalogConfig.TempFile.AbsolutePath, catalog);
            }
            else
            {
                originalFilePath = Path.Combine(originalCatalogConfig.DestFile.AbsolutePath, catalog);
            }
            originalFilePath = Path.Combine(originalFilePath, filename);

            //获取目标目录
            string newFilePath = "";
            if (newVisitCatalog == VisitCatalog.TempCatalog)
            {
                newFilePath = Path.Combine(newCatalogConfig.TempFile.AbsolutePath, catalog);
            }
            else
            {
                newFilePath = Path.Combine(newCatalogConfig.DestFile.AbsolutePath, catalog);
            }

            if (!Directory.Exists(newFilePath))
            {
                Directory.CreateDirectory(newFilePath);
            }

            newFilePath = Path.Combine(newFilePath, filename);
            //新目录中不存在且被复制前目录存在,则执行复制操作
            if (!File.Exists(newFilePath) && File.Exists(originalFilePath))
            {
                File.Copy(originalFilePath, newFilePath, true);
            }

            //获取新正式文件相对路径
            string urlFilePath = Path.Combine(newCatalogConfig.DestFile.RelativePath, catalog);
            urlFilePath = Path.Combine(urlFilePath, filename).Replace("\\", "/");

            return urlFilePath;
        }
        #endregion

        /// <summary>
        /// 批量将图片保存到正式目录中,并返回新的文件名
        /// </summary>
        /// <param name="photoList">图片完全可访问路径名，多个文件中间用;隔开</param>
        /// <returns></returns>
        public static string SaveToTargetCatalog(string photoList, string key)
        {
            if (string.IsNullOrEmpty(photoList))
            {
                return "";
            }
            List<string> urlList = new List<string>();

            string[] photoSplit = photoList.Split(';');
            foreach (var url in photoSplit)
            {
                string[] urlSplit = url.Split('/');
                if (urlSplit.Length > 2)
                {
                    //文件目录
                    string catalog = urlSplit[urlSplit.Length - 2];
                    //文件名
                    string fileName = urlSplit[urlSplit.Length - 1];

                    if (!string.IsNullOrEmpty(catalog) && !string.IsNullOrEmpty(fileName))
                    {
                        CopyFile(key, catalog, fileName);
                        urlList.Add(string.Format("/{0}/{1}", catalog, fileName));
                    }
                }
            }

            return string.Join(";", urlList);
        }

        /// <summary>
        /// 批量将图片保存到正式目录中,并返回新的文件名
        /// </summary>
        /// <param name="photoList">需要复制的图片源</param>
        /// <param name="originalKey">需要复制的路径Key</param>
        /// <param name="originalVisitCatalog">需要复制的路径类型（临时/正式）</param>
        /// <param name="newKey">复制之后的新路径Key</param>
        /// <param name="newVisitCatalog">复制之后的新路径类型（临时/正式）</param>
        /// <returns></returns>
        public static string SaveToTargetCatalog(string photoList, string originalKey, VisitCatalog originalVisitCatalog,
            string newKey, VisitCatalog newVisitCatalog)
        {
            if (string.IsNullOrEmpty(photoList))
            {
                return "";
            }
            List<string> urlList = new List<string>();

            string[] photoSplit = photoList.Split(';');
            foreach (var url in photoSplit)
            {
                string[] urlSplit = url.Split('/');
                if (urlSplit.Length > 2)
                {
                    //文件目录
                    string catalog = urlSplit[urlSplit.Length - 2];
                    //文件名
                    string fileName = urlSplit[urlSplit.Length - 1];

                    if (!string.IsNullOrEmpty(catalog) && !string.IsNullOrEmpty(fileName))
                    {
                        CopyFile(originalKey, VisitCatalog.TempCatalog, newKey, VisitCatalog.DestCatalog, catalog, fileName);
                        urlList.Add(string.Format("/{0}/{1}", catalog, fileName));
                    }
                }
            }

            return string.Join(";", urlList);
        }
        /// <summary>
        /// 通过图片链接地址下载图片
        /// </summary>
        /// <param name="key"></param>
        /// <param name="imgUrl"></param>
        /// <param name="needToCripImage">是否需要裁剪</param>
        /// <returns></returns>
        public static string DownLoadByImgUrl(string key, string imgUrl, bool needToCripImage)
        {
            var catalog = DateTime.Now.ToString("yyyyMMdd");

            string catalogName = "";
            CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];
            string fileAbsolutePath = catalogConfig.DestFile.AbsolutePath;
            //获取文件目录，文件名
            var catalogFileName = imgUrl.Split('/');
            var fileName = catalogFileName[catalogFileName.Length - 1];

            catalogName = string.Format("/{0}/{1}", catalog, fileName);
            string filePath = string.Format("{0}\\{1}\\{2}", fileAbsolutePath, catalog, fileName);
            //如果文件不存在，则下载文件
            if (!File.Exists(filePath))
            {
                if (!Directory.Exists(Path.Combine(fileAbsolutePath, catalog)))
                    Directory.CreateDirectory(Path.Combine(fileAbsolutePath, catalog));
                Path.GetExtension(imgUrl);
                DownLoadImage(imgUrl, filePath);


            }
            if (needToCripImage)//需要裁剪
            {
                catalogName = CripImageBySize(filePath, key, catalog, fileName);
            }
            return catalogName;
        }
        #region 下载指定网络路径图片
        /// <summary>
        /// 下载指定网络路径图片
        /// </summary>
        /// <param name="downloadUrl">网络图片地址</param>
        /// <param name="fileName">保存文件名(包含文件后缀)</param>
        /// <returns></returns>
        public static void DownLoadImage(string downloadUrl, string fileName)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(downloadUrl) as HttpWebRequest;
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();

            //创建本地文件写入流
            Stream stream = new FileStream(fileName, FileMode.Create);

            byte[] bArr = new byte[1024];
            int size = responseStream.Read(bArr, 0, (int)bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, (int)bArr.Length);
            }
            stream.Close();
            responseStream.Close();
        }
        #endregion
        /// <summary>
        /// 裁剪图片并保存
        /// </summary>
        public static string CripImageBySize(string filePath, string key, string catalog, string fileName)
        {
            CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];

            Image originalImage = Image.FromFile(filePath);
            int originImgWidth = originalImage.Size.Width;
            int originImgHeight = originalImage.Size.Height;

            string catalogName = string.Format("/{0}/{1}", catalog, fileName);
            Bitmap b = new Bitmap(originImgWidth, 450);
            if (originImgHeight > 450)
            {
                try
                {
                    using (Graphics g = Graphics.FromImage(b))
                    {
                        //清空画布并以透明背景色填充
                        g.Clear(Color.Transparent);
                        //在指定位置并且按指定大小绘制原图片的指定部分
                        g.DrawImage(originalImage, new Rectangle(0, 0, b.Width, b.Height), new Rectangle(0, 0, b.Width, b.Height), GraphicsUnit.Pixel);
                        //Image displayImage = new Bitmap(b, originImgWidth, originImgHeight);
                        Image displayImage = new Bitmap(b, b.Width, b.Height);
                        //CommonUtil.GUID
                        string extensionName = Path.GetExtension(filePath);
                        fileName = Guid.NewGuid().ToString("N") + extensionName;

                        string newFilePath = Path.Combine(catalogConfig.DestFile.AbsolutePath, catalog, fileName);
                        displayImage.Save(newFilePath);
                        catalogName = string.Format("/{0}/{1}", catalog, fileName);
                        //Bitmap bit = new Bitmap(b, dto.maxWidth, dto.maxHeight);
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Error("裁剪图片失败:" + e.Message);
                }
                finally
                {
                    originalImage.Dispose();
                    b.Dispose();
                }
            }

            return catalogName;
        }
        public static string GetG2MFileUrl(string mFile, string key)
        {
            List<string> urllist = new List<string>();
            CatalogElement catalogElement = FileCatalogHelper.Catalog[key];
            if (string.IsNullOrEmpty(mFile))
            {
                return "";
            }
            mFile = string.IsNullOrEmpty(mFile) ? "" : mFile.Replace("\\", "/");
            string[] mfileSplit = mFile.Split(';');
            foreach (string item in mfileSplit)
            {
                if (item.IndexOf("http") == 0)
                {
                    urllist.Add(item);
                }
                else
                {
                    urllist.Add(string.Format("{0}{1}", catalogElement.DestFile.RelativePath, item));
                }
            }

            return string.Join(";", urllist);
        }
        /// <summary>
        /// 通过图片链接地址下载图片并返回完整的绝对路径
        /// </summary>
        /// <param name="key"></param>
        /// <param name="imgUrl"></param>
        /// <returns></returns>
        public static string DownLoadTaoBaoProductImgUrl(string key, string imgUrl)
        {
            var catalog = DateTime.Now.ToString("yyyyMMdd");
            CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];
            string fileAbsolutePath = catalogConfig.TempFile.AbsolutePath;
            //获取文件目录，文件名
            var catalogFileName = imgUrl.Split('/');
            var fileName = catalogFileName[catalogFileName.Length - 1];

            string filePath = string.Format("{0}\\{1}\\{2}", fileAbsolutePath, catalog, fileName);
            //如果文件不存在，则下载文件
            if (!File.Exists(filePath))
            {
                if (!Directory.Exists(Path.Combine(fileAbsolutePath, catalog)))
                    Directory.CreateDirectory(Path.Combine(fileAbsolutePath, catalog));
                Path.GetExtension(imgUrl);
                DownLoadImage(imgUrl, filePath);

            }

            return filePath;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="files">文件绝对路径集合</param>
        /// <param name="key">保存文件的目录</param>
        /// <param name="time">每帧的时间(毫秒)/ms</param>
        /// <param name="repeat">是否重复</param>
        public static string ImgConvertToGif(List<string> files, int time, bool repeat, string key, string catalog)
        {
            CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];
            string filePath = Path.Combine(catalogConfig.TempFile.AbsolutePath, catalog);
            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            string fileName = Guid.NewGuid().ToString("N") + ".gif";
            string giffile = Path.Combine(filePath, fileName);

            AnimatedGifEncoder e = new AnimatedGifEncoder();
            e.Start(giffile);

            //每帧播放时间
            e.SetDelay(time);

            //-1：不重复，0：重复
            e.SetRepeat(repeat ? 0 : -1);

            for (int i = 0, count = files.Count; i < count; i++)
            {
                //   Image.FromStream(
                try
                {
                    e.AddFrame(NetImgUriToImage(files[i]));
                }
                catch (Exception ex)
                {
                    continue;
                }
                //Image.FromFile(files[i]);
            }

            e.Finish();

            return fileName;
        }
        public static Image NetImgUriToImage(string imgUrl)
        {
            WebRequest request = WebRequest.Create(imgUrl);
            WebResponse response = request.GetResponse();
            Stream s = response.GetResponseStream();
            byte[] data = new byte[1024];
            int length = 0;
            MemoryStream ms = new MemoryStream();
            while ((length = s.Read(data, 0, data.Length)) > 0)
            {
                ms.Write(data, 0, length);
            }
            ms.Seek(0, SeekOrigin.Begin);

            return Image.FromStream(ms);
        }
        public static void GetCatalogFileName(string qrcodePath, out string catalog, out string fileName)
        {
            if (string.IsNullOrEmpty(qrcodePath))
            {
                catalog = "";
                fileName = "";
            }

            string[] path = qrcodePath.Replace("\\", "/").Split('/');

            if (path.Length > 1)
            {
                catalog = path[path.Length - 2];
                fileName = path[path.Length - 1];
            }
            else
            {
                catalog = "";
                fileName = "";
            }

        }
    }
    public enum VisitCatalog
    {
        //临时目录
        TempCatalog = 1,
        //正式目录
        DestCatalog = 2
    }
}
